package com.test.base.mq;

import java.util.UUID;

import javax.annotation.PostConstruct;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 消息提供者
 * @author: 许自辉     
 * @date: 2018年7月2日 下午8:36:54
 */
@Component
@Slf4j
public class MessageProvider
		implements
			RabbitTemplate.ConfirmCallback,
			ReturnCallback {

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@PostConstruct
	public void init() {
		rabbitTemplate.setConfirmCallback(this);
		rabbitTemplate.setReturnCallback(this);
	}

	// 消息发送确认回调方法
	@Override
	public void confirm(CorrelationData correlationData, boolean ack,
			String cause) {
		log.info(cause + "消息发送成功:" + correlationData);
	}

	// 消息发送失败回调方法
	@Override
	public void returnedMessage(Message message, int replyCode,
			String replyText, String exchange, String routingKey) {
		log.error("消息发送失败:" + new String(message.getBody()));
	}

	/**
	 * 发送消息，不需要实现任何接口，供外部调用
	 *
	 * @param messageVo
	 */
	public void send(MessageVO messageVo) {
		CorrelationData correlationId = new CorrelationData(
				UUID.randomUUID().toString());
		rabbitTemplate.convertAndSend(QueueConstants.MESSAGE_EXCHANGE,
				QueueConstants.MESSAGE_ROUTE_KEY, messageVo, correlationId);
	}
}